import { SchemaFactory, Schema, Prop } from '@nestjs/mongoose'
import mongoose, { Document } from 'mongoose'

export type commentDocument = Comment & Document

@Schema({ timestamps: true })
export class Comment {
  @Prop({ required: true })
  content: string
  //发布评论者
  @Prop({ required: true, ref: 'User' })
  user: mongoose.Types.ObjectId
  //再xx帖子里发布
  @Prop({ required: true, ref: 'Proposition' })
  proposition: mongoose.Types.ObjectId
  //点赞数
  @Prop({ default: 0 })
  likeCount: number
  //是否点赞
  @Prop({ default: false })
  isLike: boolean
}

const commentSchema = SchemaFactory.createForClass(Comment)
commentSchema.pre('remove', async function () {
  //删除关联的点赞集合doc
  const like = await this.$model('Like').find({ comment: this._id.toString(), proposition: null })
  like.forEach(async (doc) => {
    await doc.remove()
  })
})
export { commentSchema }
